package com.lwc.common.controller;

import com.lwc.common.bean.ResultBean;
import com.lwc.common.exceotion.ValidateException;
import com.lwc.common.untils.RestStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;


import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class BaseController {
    /**
     *
     * @param msg 消息描述
     * @return
     */
    protected ResultBean success(String msg){
       return hander(RestStatus.SUCCESS,msg,null);
    }

    /**
     *
     * @param msg
     * @param data 接口数据
     * @return
     */
    protected ResultBean success(String msg,Object data){
        return hander(RestStatus.SUCCESS,msg,data);
    }

    protected  ResultBean fail(String msg){
        return  hander(RestStatus.FAIL,msg,null);
    }
    protected  ResultBean fail(String msg,Object data){
        return  hander(RestStatus.FAIL,msg,data);
    }
    protected ResultBean  getResultupdate(int rs){
 return  rs==1?success("修改成功"):fail("修改失败");
    }

    protected  void  validate(BindingResult result){
        //获取错误字段
        List<FieldError>list=result.getFieldErrors();
        Map error =new HashMap<>();
if (null!=list&&list.size()>0){
    list.forEach(a->{
        error .put(a.getField(),a.getDefaultMessage());
    });
    throw  new ValidateException(error);
}
    }

    ResultBean hander(RestStatus status,String msg,Object data){
        return  new ResultBean(status.getCode(),msg,data);
    }


}
